<template>
  <div style="width: 600px;height: 600px;" id="myDiv">
  </div>
</template>

<script>
import * as echarts from '../../assets/echarts.min.js'
import axios from 'axios'
import { onMounted } from 'vue'

export default {
  name: 'HelloWorld',
  setup() {

    // 生命周期函数，项目启动时会自动运行
    onMounted(() => {
      datainit()  // 调用初始化的方法
    });

    let dataAll = []
    var bool = false;
    var zhi = 0;
    // 初始化的方法
    const datainit = () => {
      var url = '/api/data/list7'
      // 请求后端接口
      axios.get(url).then(res => {

        var data = res.data.data.data
        // console.log(data)
        for (let i in data) {
          for (let j in dataAll) {
            if (dataAll[j].name == data[i].region) {
              dataAll[j].value = dataAll[j].value + data[i].priceSale
              bool = true
            }
          }
          if (!bool) {
            let map = { name: data[i].region, value: data[i].priceSale }
            dataAll.push(map)
          }
          bool = false
        }
        // 对dataAll中的value进行降序排序
        dataAll.sort((a, b) => b.value - a.value)
        // console.log(dataAll)
        dataAll = dataAll.slice(0, 2)  //取出前多少个（这里是前两个）
        let citys = []
        let buys = []
        for (let j in dataAll) {
          citys.push(dataAll[j].name)
          buys.push(dataAll[j].value)
        }

        console.log(citys)
        console.log(buys)

        // for (let i in data) {
        //   for (let j in dataAll) {
        //     if (data[i].region == dataAll[j].name) {
        //       bool = true
        //       zhi = j
        //       break
        //     } else {
        //       bool = false
        //     }
        //   }
        //   if (bool) {
        //     dataAll[zhi].priceSale += data[i].priceSale
        //   } else {
        //     dataAll.push({ name: data[i].region, value: data[i].priceSale })
        //   }
        // }


        // 图表的初始化，放在数据获取成功后
        init(citys, buys);

      })


    };

    // 初始化图表
    const init = (citys, buys) => {
      var options = {
        title: {
          text: '柱状图展示2020年消费额最高的5个地区'
        },
        xAxis: {
          data: citys,
          name: '地区'
        },
        yAxis: {
          name: '消费额'
        },
        series: {
          data: buys,
          type: 'bar'
        }
      }


      let myChart = echarts.init(document.getElementById("myDiv"));
      myChart.setOption(options)

    }




  }




}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>
